package okhttp3Demo.interceptor;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.*;

import java.io.IOException;

/**
 * Created by lining on 2018/5/8.
 */
public class ProgressRequestBody extends RequestBody {
    private RequestBody requestBody;
    //进度回调接口
    private ProgressRequestListener progressListener;
    //包装完成的BufferedSink
    private BufferedSink bufferedSink;



    public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) {
        this.requestBody = requestBody;
        this.progressListener = progressListener;
    }

    @Override
    public long contentLength() throws IOException {
        return requestBody.contentLength();
    }

    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (bufferedSink == null) {
            //包装
            bufferedSink = Okio.buffer(sink(sink));
        }
        //写入
        requestBody.writeTo(bufferedSink);
        //必须调用flush，否则最后一部分数据可能不会被写入
        bufferedSink.flush();
    }

    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            //当前写入字节数
            long bytesWritten = 0L;
            //总字节长度，避免多次调用contentLength()方法
            long contentLength = 0L;
            long progress = 0L;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if (contentLength == 0) {
                    //获得contentLength的值，后续不再调用
                    contentLength = contentLength();
                }
                //增加当前写入的字节数
                bytesWritten += byteCount;
                //回调
                if(progressListener != null){
                    if( contentLength > 0){
                        long currProgress = bytesWritten * 100 / contentLength;
                        if(currProgress > progress){
                            progress = currProgress;
                            progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength);
                        }
                    }
                }
            }
        };
    }
}
